package com.cloud.rou.im.connection.container.repository;

import com.cloud.rou.im.connection.container.connection.Connection;
import com.cloud.rou.im.connection.container.connection.UserIdAttributeKey;
import com.cloud.rou.im.connection.container.session.Session;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2019-11-09 19:31
 */
public class InMemoryUserConnectorRepository implements UserConnectorRepository {
    private static final Logger logger = LoggerFactory.getLogger(InMemoryUserConnectorRepository.class);

    protected ConcurrentMap<Long, Session> connMap;

    public InMemoryUserConnectorRepository() {
        this.connMap = new ConcurrentHashMap<>();
    }

    @Override
    public Session getConnectSession(ChannelHandlerContext ctx) {
        Long userId = ctx.channel().attr(UserIdAttributeKey.USER_ID).get();
        if (userId == null) {
            return null;
        }
        return connMap.get(userId);
    }

    @Override
    public Session getConnectSession(Long netId) {
        return connMap.get(netId);
    }

    @Override
    public void addConnectSession(Session session) {
        connMap.put(session.getUserId(), session);
    }

    @Override
    public void removeConnectSession(Long userId) {
        connMap.remove(userId);
    }

    @Override
    public void removeConnectSession(ChannelHandlerContext ctx) {
        Long userId = ctx.channel().attr(UserIdAttributeKey.USER_ID).get();
        if (userId != null) {
            connMap.remove(userId);
        }
    }

    @Override
    public void removeAllConnectSession() {
        connMap.clear();
    }
}
